package com.oromwin.repos.server.request.volume;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Common;
import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.helper.DBHelper;
import com.oromwin.repos.common.helper.IOHelper;
import com.oromwin.repos.data.AbstractReposTable;
import com.oromwin.repos.data.VolumeTable;
import com.oromwin.repos.server.LockObject;
import com.oromwin.repos.server.request.AbstractRequest;
import com.oromwin.repos.server.response.CreateResponse;
import com.oromwin.repos.server.response.Response;

public class CreateVolumeRequest extends AbstractRequest {
    private Log log = Logger.getLog(CreateVolumeRequest.class);
    private String VolumeName = null;

    @Override
    public void receive(DataInputStream dis, LockObject lockObject) throws ReposException {
        try {
            VolumeName = IOHelper.readUTF8(dis);
        } catch (IOException e) {
            throw ReposException.create(log, e);
        }
    }

    @Override
    public Response run() throws ReposException {
        CreateResponse res = null;
        try {
            checkDependentObjectNotExists();
            _volumeTable = new VolumeTable(id(), VolumeName, Boolean.FALSE, Common.datetime(), Common.datetime());
            DBHelper.insertTable(_volumeTable);
            res = new CreateResponse(true, "Succeeded to create volume", id());
        } catch (ReposException e) {
            res = new CreateResponse(false, e.getMessage(), id());
        } catch (Exception e) {
            String message = String.format("Unexpected exception, {%s}", e.getMessage());
            throw ReposException.create(log, e, message);
        }
        return res;
    }

    @Override
    public void checkDependentObjectNotExists() throws ReposException {
        String whereClause = String.format("VolumeName = '%s' AND VolumeStatus = 0", VolumeName);
        List<AbstractReposTable> list = DBHelper.selectTable(VolumeTable.class, whereClause);
        if (list.size() != 0) {
            String message = String.format("'%s' VolumeName is already exists at server", VolumeName);
            throw ReposException.create(log, message); 
        }
    }
}
